<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="药品名称" prop="drugName">
        <el-input
            v-model="queryParams.drugName"
            placeholder="请输入药品名称"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>

      <el-form-item label="药品状态" prop="drugState"   style="width: 250px;">
        <el-select v-model="queryParams.drugState" placeholder="请选择药品状态" clearable>
          <el-option label="库存充足" value="库存充足" />
          <el-option label="库存不足" value="库存不足" />
        </el-select>
      </el-form-item>


      <el-form-item label="药品类型" prop="drugType" style="width: 250px;">
        <el-select v-model="queryParams.drugType" placeholder="请选择药品类型" clearable>
          <el-option
              v-for="dict in medicine_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        <el-button type="success" icon="Refresh" @click="handleBatchUpdate">批量更新状态</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['medicine:medicineStocks:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['medicine:medicineStocks:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['medicine:medicineStocks:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['medicine:medicineStocks:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="medicineStocksList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
<!--      <el-table-column label="药品Id" align="center" prop="drugId" />-->
      <el-table-column label="药品名称" align="center" prop="drugName" />
      <el-table-column label="药品描述" align="center" prop="drugInfo" />
      <el-table-column label="药品库存" align="center" prop="drugInventory" />
      <el-table-column label="预警阈值" align="center" prop="lowStockThreshold" />
      <el-table-column label="药品类型" align="center" prop="drugType">
        <template #default="scope">
          <dict-tag :options="medicine_type" :value="scope.row.drugType"/>
        </template>
      </el-table-column>
      <el-table-column label="药品状态" align="center" prop="drugState">
        <template #default="scope">
          <el-tag :type="scope.row.drugState === '库存不足' ? 'danger' : 'success'">
            {{ scope.row.drugState }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['medicine:medicineStocks:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['medicine:medicineStocks:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改商品库存对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="medicineStocksRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="药品名称" prop="drugName">
          <el-input v-model="form.drugName" placeholder="请输入药品名称" />
        </el-form-item>
        <el-form-item label="药品描述" prop="drugInfo">
          <el-input v-model="form.drugInfo" placeholder="请输入药品描述" />
        </el-form-item>
        <el-form-item label="药品库存" prop="drugInventory">
          <el-input-number v-model="form.drugInventory" controls-position="right" :min="0" />
        </el-form-item>
        <el-form-item label="预警阈值" prop="lowStockThreshold">
          <el-input-number v-model="form.lowStockThreshold" controls-position="right" :min="0" />
        </el-form-item>
        <el-form-item label="药品类型" prop="drugType">
          <el-select v-model="form.drugType" placeholder="请选择药品类型">
            <el-option
                v-for="dict in medicine_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="MedicineStocks">
import { listMedicineStocks, getMedicineStocks, delMedicineStocks, addMedicineStocks, updateMedicineStocks } from "@/api/medicine/medicineStocks"

const { proxy } = getCurrentInstance()
const { medicine_type } = proxy.useDict('medicine_type')

const medicineStocksList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    drugName: null,
    drugInfo: null,
    drugInventory: null,
    drugType: null,
    drugState: null
  },
  rules: {
    drugName: [{ required: true, message: "药品名称不能为空", trigger: "blur" }],
    drugInventory: [{ required: true, message: "药品库存不能为空", trigger: "blur" }],
    lowStockThreshold: [{ required: true, message: "预警阈值不能为空", trigger: "blur" }]
  }
})

// 添加库存不足弹窗相关的响应式数据
const stockWarningDialog = ref(false)
const insufficientMedicines = ref([])
const countdown = ref(5)
let countdownTimer = null



const { queryParams, form, rules } = toRefs(data)

/// ... existing code ...
/** 查询商品库存列表 */
function getList() {
  loading.value = true
  listMedicineStocks(queryParams.value).then(response => {
    medicineStocksList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 页面加载时检查是否需要刷新
onMounted(() => {
  if (localStorage.getItem('medicineStocksNeedRefresh') === 'true') {
    getList()
    localStorage.removeItem('medicineStocksNeedRefresh')
  }
})

// 当通过路由切换回到页面时也检查是否需要刷新
onActivated(() => {
  if (localStorage.getItem('medicineStocksNeedRefresh') === 'true') {
    getList()
    localStorage.removeItem('medicineStocksNeedRefresh')
    proxy.$modal.msgSuccess("药品库存已更新")
  }
})
// ... existing code ...


// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    drugId: null,
    drugName: null,
    drugInfo: null,
    drugInventory: null,
    lowStockThreshold: 10, // 默认阈值为10
    drugType: null,
    drugState: "库存充足"
  }
  proxy.resetForm("medicineStocksRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.drugId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加商品库存"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _drugId = row.drugId || ids.value
  getMedicineStocks(_drugId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改药品库存"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["medicineStocksRef"].validate(valid => {
    if (valid) {
      // 根据库存和阈值自动设置状态
      if (form.value.drugInventory < form.value.lowStockThreshold) {
        form.value.drugState = "库存不足"
      } else {
        form.value.drugState = "库存充足"
      }

      if (form.value.drugId != null) {
        updateMedicineStocks(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addMedicineStocks(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _drugIds = row.drugId || ids.value
  proxy.$modal.confirm('是否确认删除商品库存编号为"' + _drugIds + '"的数据项？').then(function() {
    return delMedicineStocks(_drugIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('medicine/medicineStocks/export', {
    ...queryParams.value
  }, `medicineStocks_${new Date().getTime()}.xlsx`)
}

/** 批量更新状态 */
function handleBatchUpdate() {
  proxy.$modal.confirm('是否确认批量更新所有药品的库存状态？').then(function() {
    // 这里需要调用后端的批量更新接口
    // return updateMedicineStocksStates()
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("批量更新成功")
  }).catch(() => {})
}


// 处理库存不足错误的函数
function handleInsufficientStockError(errorMessage) {
  // 解析错误信息中的药品名称
  // 假设错误信息格式为 "药品A库存不足,药品B库存不足"
  const medicines = errorMessage.split(',').map(item => {
    // 提取药品名称（去除"库存不足"字样）
    return item.replace('库存不足', '').trim();
  }).filter(item => item.length > 0);

  if (medicines.length > 0) {
    insufficientMedicines.value = medicines;
    stockWarningDialog.value = true;
    startCountdown();
  } else {
    proxy.$modal.msgError("药品库存不足，请联系管理员");
  }
}

// 开始倒计时
function startCountdown() {
  countdown.value = 5;
  if (countdownTimer) {
    clearInterval(countdownTimer);
  }
  countdownTimer = setInterval(() => {
    countdown.value--;
    if (countdown.value <= 0) {
      closeStockWarningDialog();
    }
  }, 1000);
}

// 关闭库存警告弹窗
function closeStockWarningDialog() {
  stockWarningDialog.value = false;
  insufficientMedicines.value = [];
  if (countdownTimer) {
    clearInterval(countdownTimer);
    countdownTimer = null;
  }
}


getList()
</script>
